package com.dl.blog.service.impl;

import com.dl.blog.entity.VisitLog;
import com.dl.blog.entity.VisitPage;
import com.dl.blog.entity.VisitRecordDTO;
import com.dl.blog.entity.VisitorInfo;
import com.dl.blog.mapper.VisitLogMapper;
import com.dl.blog.mapper.VisitPageMapper;
import com.dl.blog.mapper.VisitorInfoMapper;
import com.dl.blog.service.VisitService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class VisitServiceImpl implements VisitService {

    private static final Logger log = LoggerFactory.getLogger(VisitServiceImpl.class);
    @Autowired
    private VisitLogMapper visitLogMapper;

    @Autowired
    private VisitorInfoMapper visitorInfoMapper;

    @Autowired
    private VisitPageMapper visitPageMapper;

    @Autowired
    private ApiServiceImpl apiService;

    @Override
    public void recordVisit(VisitRecordDTO recordDTO, String clientIp, String userAgent) {
        System.out.println("recordDTO = " + recordDTO);
        System.out.println("clientIp = " + clientIp);

        // 解析User-Agent获取浏览器和操作系统信息
        UserAgent userAgentInfo = UserAgent.parseUserAgentString(userAgent);
        Browser browser = userAgentInfo.getBrowser();
        OperatingSystem os = userAgentInfo.getOperatingSystem();

        System.out.println("browser = " + browser);
        System.out.println("os = " + os);

        String visitorId = recordDTO.getVisitorId();
        String siteId = recordDTO.getSiteId();
        String locationInfo = recordDTO.getLocationInfo();

        // 保存或更新访问者信息
        saveOrUpdateVisitorInfo(visitorId, clientIp, userAgentInfo, locationInfo);

        // 获取或创建页面信息
        VisitPage visitPage = getOrCreatePageInfo(siteId, recordDTO.getPageUrl(),
                recordDTO.getRelativePath(),
                recordDTO.getPageTitle());

        // 保存访问日志
        saveVisitLog(visitorId, visitPage.getId(), clientIp, userAgent, recordDTO);
    }

    private void saveOrUpdateVisitorInfo(String visitorId, String clientIp, UserAgent userAgentInfo, String locationInfo) {
        // 先查询是否已有该访问者信息
        VisitorInfo visitorInfo = visitorInfoMapper.selectByVisitorId(visitorId);

        if (visitorInfo == null) {
/*            JSONObject locationByIp = apiService.getLocationByIp();
            JSONObject info = (JSONObject) locationByIp.get("info");
            String country = info.getString("country");
            String prov = info.getString("prov");
            String city = info.getString("city");
            String isp = info.getString("isp");
            // 中国-湖北省-武汉市-电信
            String locationInfo = country + "-" + prov + "-" + city + "-" + isp;*/

            // 新访问者，插入记录
            visitorInfo = new VisitorInfo();
            visitorInfo.setLocationInfo(locationInfo);

            visitorInfo.setVisitorId(visitorId);
            visitorInfo.setFirstVisitTime(new Date());
            visitorInfo.setLastVisitTime(new Date());
            visitorInfo.setVisitCount(1);

            // 从UserAgent解析浏览器信息
            visitorInfo.setBrowserName(userAgentInfo.getBrowser().getName());
            visitorInfo.setBrowserVersion(userAgentInfo.getBrowserVersion().getVersion());

            // 从UserAgent解析操作系统信息
            visitorInfo.setOsName(userAgentInfo.getOperatingSystem().getName());
            visitorInfo.setIpAddress(clientIp);

            // 从UserAgent解析设备类型
            String deviceType = userAgentInfo.getOperatingSystem().getDeviceType().getName();
            visitorInfo.setDeviceType(deviceType);

            log.info("插入访问者信息：{}", visitorInfo);
            visitorInfoMapper.insert(visitorInfo);
        } else {
            // 已有记录，更新访问次数和最后访问时间
            visitorInfo.setVisitCount(visitorInfo.getVisitCount() + 1);
            visitorInfo.setLastVisitTime(new Date());
            visitorInfoMapper.update(visitorInfo);
        }
    }

    private VisitPage getOrCreatePageInfo(String siteId, String pageUrl, String relativePath, String pageTitle) {
        // 先查询页面是否已存在
        VisitPage visitPage = visitPageMapper.selectByUrlAndSiteId(siteId, pageUrl);

        if (visitPage == null) {
            // 页面不存在，创建新记录
            visitPage = new VisitPage();
            visitPage.setSiteId(siteId);
            visitPage.setPageUrl(pageUrl);
            visitPage.setRelativePath(relativePath);
            visitPage.setPageTitle(pageTitle);
            visitPage.setCreateTime(new Date());

            visitPageMapper.insert(visitPage);

            // 注意：这里需要获取插入后的ID，根据MyBatis配置方式可能需要调整
            // 简单起见，假设insert后ID已回填到visitPage对象中
        }

        return visitPage;
    }

    private void saveVisitLog(String visitorId, Long pageId, String clientIp, String userAgent, VisitRecordDTO recordDTO) {
        VisitLog visitLog = new VisitLog();
        visitLog.setSiteId(recordDTO.getSiteId());
        visitLog.setPageId(pageId);
        visitLog.setVisitorId(visitorId);
        visitLog.setIpAddress(clientIp);
        visitLog.setUserAgent(userAgent);
        visitLog.setReferer(recordDTO.getReferer());
        visitLog.setVisitTime(new Date());
        visitLogMapper.insert(visitLog);
    }
}
